//
//  FocusCell.swift
//  DYSwiftFramework
//
//  Created by huangdeyu on 2021/11/1.
//  Copyright © 2021 none. All rights reserved.
//

import UIKit
import Kingfisher
import ZLPhotoBrowser

private class _FocusCellHeader:UIView {
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var avatar = UIImageView()
    lazy var titleLbl = UILabel()
    lazy var timeLbl = UILabel.init()
    lazy var shopBtn = UIButton.init(type: .custom)
    lazy var focusBtn = UIButton.init(type: .custom)
    
    init() {
        super.init(frame: CGRect.zero)
        avatar.frame = CGRect.init(x: 0, y: 0, width: 40, height: 40)
        avatar.roundCorners(.allCorners, radius: 20)
       
        titleLbl.font = UIFont.boldSystemFont(ofSize: 14)
        titleLbl.textColor = UIColor.black
        timeLbl.font  = UIFont.systemFont(ofSize: 10)
        timeLbl.textColor = UIColor.lightGray
        
        focusBtn.setTitle("+ 关注", for: .normal)
        focusBtn.setTitleColor(UIColor.init(hex: 0xfa3c3c), for: .normal)
        focusBtn.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        focusBtn.layerBorderColor = UIColor.init(hex: 0xfa3c3c)
        focusBtn.layerBorderWidth = 0.5
        focusBtn.layerCornerRadius = 12
        focusBtn.onTap = {[weak self] (button) in
            
        }
        
        setupUI()
    }
    
    private func setupUI() {
        
        let stack1 = UIStackView.init(arrangedSubviews: [titleLbl,timeLbl])
        stack1.axis = .vertical
        stack1.distribution = .equalCentering
        addSubview(stack1)
        
        
        let stackView = UIStackView.init(arrangedSubviews: [avatar,stack1,UIView(),focusBtn])
        stackView.alignment = .center
        stackView.distribution = .fill
        stackView.spacing = 10
        avatar.snp.makeConstraints { (m) in
            m.width.height.equalTo(40)
        }
        focusBtn.snp.makeConstraints { (m) in
            m.width.equalTo(60)
            m.height.equalTo(24)
        }
        
        addSubview(stackView)
        stackView.snp.makeConstraints { (m) in
            m.edges.equalToSuperview().inset(12)
        }
    }
    func loadData(item:RecList)  {
        titleLbl.text = item.nickName ?? ""
        if let url = URL.init(string: item.headImg ?? "") {
            avatar.kf.setImage(with: .network(url))
        }
    }
}


private class _FocusCellContent:UIView {
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var titleLbl = InteractLabel.init()
    lazy var showMore = UIButton.init(type: .custom)
    var item:RecList?
    
    init() {
        super.init(frame: CGRect.zero)
        titleLbl.numberOfLines = 0
        showMore.addTarget(self, action: #selector(showMoreClicked), for: .touchUpInside)
        showMore.setTitle("展开", for: .normal)
        showMore.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        showMore.setTitleColor(UIColor.systemBlue, for: .normal)
        showMore.isHidden = true
        setupUI()
    }
    private func setupUI() {
        let stack = UIStackView(arrangedSubviews: [titleLbl,showMore])
        stack.axis = .vertical
        stack.alignment = .top
        addSubview(stack)
        stack.snp.makeConstraints { (m) in
            m.top.bottom.equalToSuperview()
            m.left.right.equalToSuperview().inset(12)
        }
    }
    
    @objc func showMoreClicked()  {
        if let i = item {
            i.showMore = !i.showMore
            if i.showMore {
                showMore.setTitle("收起", for: .normal)
            } else {
                showMore.setTitle("展开", for: .normal)
            }
            i.cacheHeight = nil
            tableView?.reloadRows(at: [IndexPath.init(row: item!.cellIndex, section: 0)], with: .automatic)
        }
    }
    
    var tableView:UITableView? {
        var supV = self.superview
        while supV != nil {
            if supV!.isKind(of: UITableView.self) {
                return supV as? UITableView
            }
            supV = supV?.superview
        }
        return nil
    }

    
    fileprivate func loadData(_ item:RecList) {
        self.item = item
        titleLbl.attributedText = item.contentAttribute
        if let _ = item.moreThanRuleLines {
            self.dealWithUnwrapped()
        } else {
            let origin =  titleLbl.heightForAttribute(width: SCREEN_W - 24, lines: 0)
            let current = titleLbl.heightForAttribute(width: SCREEN_W, lines: 3)
            if origin > current {
                item.moreThanRuleLines = true
            } else {
                item.moreThanRuleLines = false
            }
            self.dealWithUnwrapped()
        }
    }
    
    func dealWithUnwrapped()  {
        if let more = item!.moreThanRuleLines {
            // 超过三行
            if more {
                showMore.isHidden = false
                if item!.showMore {
                    titleLbl.numberOfLines = 0
                    showMore.setTitle("收起", for: .normal)
                } else {
                    titleLbl.numberOfLines = 3
                    showMore.setTitle("展开", for: .normal)
                }
            } else {
                showMore.isHidden = true
                titleLbl.numberOfLines = 0
            }
        }
        
    }
}

// 播放器模式
class _FocusVideoView:UIView {
    var item:RecList?
    lazy var img = UIImageView.init()
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    init() {
        super.init(frame: CGRect.zero)
        addSubview(img)
        img.contentMode = .scaleAspectFill
        img.clipsToBounds = true
        img.snp.makeConstraints { (m) in
            m.left.equalToSuperview().inset(12)
            m.top.equalToSuperview().offset(6)
            m.bottom.equalToSuperview().inset(6)
            m.width.equalTo(232)
            m.height.equalTo(306).priority(.high)
        }
    }

    func loadData(item:RecList) -> Void {
        if let url = URL(string: item.videoCoverImg ?? "") {
            img.kf.setImage(with: .network(url))
        }
        if let size = item.imgDimensionList?.first {
            if size.width ?? 0 < size.height ?? 0 {
                img.snp.updateConstraints { (m) in
                    m.width.equalTo(232)
                    m.height.equalTo(306).priority(.high)
                }
            } else {
                img.snp.updateConstraints { (m) in
                    m.width.equalTo(SCREEN_W - 24)
                    m.height.equalTo((SCREEN_W - 24) * (262.0 / 351.0)).priority(.high)
                }
            }
        }
    }
}

private func previewImages(images:[String]?,index:Int) {
    var data:[Any] = []
    images?.forEach({ (item) in
        if let url = URL.init(string: item) {
            data.append(url)
        }
    })
    let vc = ZLImagePreviewController(datas: data, index: index, showSelectBtn: false,showBottomView: false) { (url) -> ZLURLType in
        return .image
    } urlImageLoader: { (url, imageView, progress, loadFinish) in
        imageView.kf.setImage(with: url) { (receivedSize, totalSize) in
            let percentage = (CGFloat(receivedSize) / CGFloat(totalSize))
            debugPrint("\(percentage)")
            progress(percentage)
        } completionHandler: { (_) in
            loadFinish()
        }
    }
    vc.doneBlock = { (datas) in
        debugPrint(datas)
    }
    vc.modalPresentationStyle = .fullScreen
    Router.rootVC.showDetailViewController(vc, sender: nil)
}

// 单图模式
class _FocusSinglePhotoView : UIView {
    var item:RecList?
    lazy var img = UIButton.init(type: .custom)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    init() {
        super.init(frame: CGRect.zero)
        addSubview(img)
        img.onTap = { [weak self] (button) in
            previewImages(images: self?.item?.imgList, index: 0)
        }
        img.snp.makeConstraints { (m) in
            m.left.equalToSuperview().inset(12)
            m.top.equalToSuperview().offset(6)
            m.bottom.equalToSuperview().inset(6)
            m.width.equalTo(232)
            m.height.equalTo(306).priority(.high)
        }
    }
    
    

    func loadData(item:RecList) -> Void {
        self.item = item
        if let url = URL(string: item.imgList?.first ?? "") {
            img.kf.setImage(with: .network(url), for: .normal)
        }
        if let size = item.imgDimensionList?.first {
            if size.width ?? 0 < size.height ?? 0 {
                img.snp.updateConstraints { (m) in
                    m.width.equalTo(232)
                    m.height.equalTo(306).priority(.high)
                }
            } else {
                img.snp.updateConstraints { (m) in
                    m.width.equalTo(SCREEN_W - 24)
                    m.height.equalTo((SCREEN_W - 24) * (262.0 / 351.0)).priority(.high)
                }
            }
        }
    }
}

// 四图模式
class _FocusFourPhotoView:UIView {
    lazy var images:[UIButton] = []
    var item:RecList?
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    init() {
        super.init(frame: CGRect.zero)
        for index in 0...3 {
            let img = UIButton.init(type: .custom)
            img.onTap = { [weak self] (btn) in
                previewImages(images: self?.item?.imgList, index: index)
            }
            images.append(img)
        }
        setupUI()
    }
    func setupUI()  {
        let stack1 = UIStackView.init(arrangedSubviews: [images[0],images[1]])
        stack1.axis = .horizontal
        stack1.spacing = 6
        addSubview(stack1)
        stack1.snp.makeConstraints { (m) in
            m.left.equalToSuperview().offset(12)
            m.top.equalToSuperview().offset(6)
            m.height.equalTo((SCREEN_W - 36) / 3.0)
        }
        
        let stack2 = UIStackView.init(arrangedSubviews: [images[2],images[3]])
        stack2.axis = .horizontal
        stack2.spacing = 6
        addSubview(stack2)
        stack2.snp.makeConstraints { (m) in
            m.left.equalToSuperview().offset(12)
            m.top.equalTo(stack1.snp_bottomMargin).offset(6)
            m.height.equalTo((SCREEN_W - 36) / 3.0)
            m.bottom.equalToSuperview()
        }
        images.forEach { (item) in
            item.snp.makeConstraints { (m) in
                m.width.equalTo((SCREEN_W - 36) / 3.0)
            }
        }
    }

    func loadData(item:RecList) -> Void {
        self.item = item
        item.imgList?.enumerated().forEach({ (index,imgStr) in
            if let url = URL(string: imgStr) {
                images[index].kf.setImage(with: .network(url),for: .normal)
            }
        })
    }
}

// 非四图模式
class _FocusMutiPhotoView: UIView {
    lazy var images:[UIButton] = []
    lazy var stacks:[UIStackView] = []
    var item:RecList?
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    init() {
        super.init(frame: CGRect.zero)
        for index in 0...8 {
            let img = UIButton.init(type: .custom)
            img.onTap = { [weak self] (btn) in
                previewImages(images: self?.item?.imgList, index: index)
            }
            images.append(img)
        }
        for index in 0...2 {
            let subViews = [images[0 + index * 3],images[1 + index * 3],images[2 + index * 3]]
            let stack = UIStackView.init(arrangedSubviews: subViews)
            stack.spacing = 6
            stack.isHidden = true
            stacks.append(stack)
        }
        self.setupUI()
    }
    
    func setupUI() {
        
        let stack = UIStackView.init(arrangedSubviews: stacks)
        addSubview(stack)
        stack.snp.makeConstraints { (m) in
            m.left.right.equalToSuperview().inset(12)
            m.bottom.equalToSuperview()
            m.top.equalToSuperview().offset(6)
        }
        stack.axis = .vertical
        stack.spacing = 6
        stacks.forEach { (s) in
            s.snp.makeConstraints { (m) in
                m.height.equalTo((SCREEN_W - 36) / 3.0)
            }
        }
        images.forEach { (img) in
            img.snp.makeConstraints { (m) in
                m.width.equalTo((SCREEN_W - 36) / 3.0)
                m.height.equalTo((SCREEN_W - 36) / 3.0)
            }
        }
    }

    func loadData(item:RecList) -> Void {
        self.item = item
        stacks.forEach { (item) in
            item.isHidden = true
        }
        if let list = item.imgList {
            // 只有一行
            if list.count < 4 {
                stacks[0].isHidden = false
            } else if list.count < 7{
                stacks[1].isHidden = false
                stacks[0].isHidden = false
            } else {
                stacks[1].isHidden = false
                stacks[0].isHidden = false
                stacks[2].isHidden = false
            }
            list.enumerated().forEach { (index,item) in
                if index > 8 {
                    return
                }
                if let url = URL(string: item) {
                    images[index].kf.setImage(with: .network(url),for: .normal)
                }
            }
        }
    
    }
}

class FocusCell: UITableViewCell {
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    fileprivate lazy var headerView = _FocusCellHeader()
    fileprivate lazy var content = _FocusCellContent()
    fileprivate lazy var singlePhoto = _FocusSinglePhotoView() // 单图模式
    lazy var fourPhoto = _FocusFourPhotoView() // 4图模式
    lazy var mutiPhoto = _FocusMutiPhotoView() // 非4图模式
    lazy var videoView = _FocusVideoView() // 播放器模式
    var model:RecList?;
    
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.selectionStyle = .none
        singlePhoto.isHidden = true
        fourPhoto.isHidden = true
        mutiPhoto.isHidden = true
        videoView.isHidden = true
        setupUI()
    }
    
    func setupUI() {
        let stack = UIStackView.init(arrangedSubviews: [headerView,content,videoView,singlePhoto,fourPhoto,mutiPhoto])
        stack.axis = .vertical
        contentView.addSubview(stack)
        stack.snp.makeConstraints { (m) in
            m.edges.equalToSuperview()
        }
    }
    
    func loadData(item:RecList)  {
        model = item;
        headerView.loadData(item: item)
        content.loadData(item)
        singlePhoto.isHidden = true
        fourPhoto.isHidden = true
        mutiPhoto.isHidden = true
        videoView.isHidden = true
        if let list = item.imgList {
            if list.count == 1 {
                singlePhoto.isHidden = false
                singlePhoto.loadData(item: item)
            } else if list.count == 4 {
                fourPhoto.isHidden = false
                fourPhoto.loadData(item: item)
            } else  if list.count > 0{
                mutiPhoto.isHidden = false
                mutiPhoto.loadData(item: item)
            }
        }
        if let _ = item.videoUrl {
            singlePhoto.isHidden = true
            videoView.isHidden = false
            videoView.loadData(item: item)
        }
    }
}
